<?php
/**
 * Created by dzw.
 * User: Administrator
 * Date: 2018-03-16
 * Time: 10:22
 */

namespace App\Http\Controllers\Web\Shop;

use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class ShopController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'shop/index'],
        'show' => ['get', 'shop/index/%d'],
        'products' => ['get', 'shop/products/%d'],
        'products_index' => ['get', 'shop/products/index/%d'],
        'third_cat' => ['get', 'shop/third_cat/%d'],
        'archives' => ['get', 'shop/archives/%d'],
        'shop' => ['get', 'shop/get_company/%d'],
        'categories' => ['get', 'shop/categories/%d'],

        'collection_check' => ['get',  'buyer/collection/checkCollection/%d/%d'], //检测商品和店铺收藏
        'shopImCheck' => ['post',  'im/shopImCheck/%d'], // 检测店铺用户是否有 IM 账户
        'attribute'=> ['get', 'shop/attribute/%d'],
    ];
    protected $api_host;

    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->api_host = config('url.api_web');
    }

    public function index()
    {
        return redirect('/');
    }

    public function show($id)
    {

        //参数部分
        $search_params = $this->request->all(['third_cat','brand_id','name','price']);
        if (isset($search_params['product_name']) && strlen($search_params['name'])>26){
            $search_params['name'] = mb_substr($search_params['name'],26);
            $search_params['character'] = true;
        }else{
            $search_params['character'] = false;
        }
        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'page' => $page,
            'orderBy'=>'id',
            'sortedBy'=>'desc',
        ];


        //请求部分
        $ret = http_web($this->api_url['show'],[$id])->send();

//        //结果处理部分
        $data = [];
        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['shop'] = $ret['data'];
        }

        //产品 请求部分
        $ret = http_web($this->api_url['products'],[$id])->send($params);
        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['product']= paginate($this->request, $ret['data']);
        }

        foreach($data['product']['list'] as $k=>$v){
           $data['product']['list'][$k]['name']=cut_str($v['name'],35);
       }

        //品类  品牌 请求部分
//        $ret = http_web($this->api_url['third_cat'],[$id])->send();
//
//        $catearr=[];
//        $cate_array=[];
//        $brandarr=[];
//        $brand_array=[];
//        foreach($ret['data'] as $k=>$v){
//           if(!in_array($v['third_cat'],$catearr)){
//               $catearr[]=$v['third_cat'];
//               $cate_array[]=[
//                   'key'=>$v['third_cat'],
//                   'name'=>$v['categories']['name']
//               ];
//
//           }
//            if(!in_array($v['brand_id'],$brandarr)){
//                $brandarr[]=$v['brand_id'];
//                $brand_array[]=[
//                   'key'=>$v['brand_id'],
//                   'name'=>$v['brand']['name']
//               ];
//            }
//        }

        //自定义分类
        $categories = http_web($this->api_url['categories'],[$id])->send();

        $data['search']=$search_params;
        $search_params['shop_id'] = $id;
        $data['search_params'] = $search_params;

        $data['categories']=$categories['data'];


        try {
            // 检测当前登录用户是否收藏过店铺
            $check = http_web($this->api_url['collection_check'], [0,$id])->send();
            $data['check'] = $check['data'];
            // 检测用户商户是否有 IM 账号
            $shop_uid = $data['shop']['user']['id'];
            $shopImCheck = http_web($this->api_url['shopImCheck'], [$shop_uid])->send();

            $data['shopImCheck'] = isset($shopImCheck['data'])?$shopImCheck['data']:false;
        }catch (\Exception $e){
            //dd($e->getMessage());
        }
        return view('web.shop.index', $data);
    }

    public function products($id)
    {
        //参数部分
        $search_params = $this->request->all(['third_cat','brand_id','name','price','custom_cate']);

        // 检测非法字符及长度 begin
//        $check = $this->CheckIllegalStr(isset($search_params['name'])?$search_params['name']:'');
//
//        if ($check==false){
//            $search_params['name'] = '';
//        }
        if (isset($search_params['name']) && strlen($search_params['name'])>26) {
            $search_params['name'] = mb_substr($search_params['name'], 0,26);
            $search_params['character'] = true;
        }else{
            $search_params['character'] = false;
        }

        $search_params['name'] = str_replace([';','eval'],' ',$search_params['name']);
        // 检测非法字符及长度 end
        $page = $this->request->get('page', 1);
        $params = [
           'search' => search_params($search_params),
           'searchJoin' => 'and',
           'page' => $page,
           'orderBy'=>'id',
           'sortedBy'=>'desc',
        ];

        //请求部分
        $ret = http_web($this->api_url['products'],[$id])->send($params);

        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['product']= paginate($this->request, $ret['data']);

        }
        foreach($data['product']['list'] as $k=>$v){
            $data['product']['list'][$k]['name']=cut_str($v['name'],35);
        }
        $data['search']=$search_params;

        //品类  品牌 请求部分
        $ret = http_web($this->api_url['third_cat'],[$id])->send();

        $catearr=[];
        $cate_array=[];
        $brandarr=[];
        $brand_array=[];
        foreach($ret['data'] as $k=>$v){
           if(!in_array($v['third_cat'],$catearr)){
               $catearr[]=$v['third_cat'];
               $cate_array[]=[
                   'key'=>$v['third_cat'],
                   'name'=>$v['categories']['name']
               ];

           }
            if(!in_array($v['brand_id'],$brandarr)){
                $brandarr[]=$v['brand_id'];
                if(!empty($v['brand']['name'])){
                    $brand_array[]=[
                          'key'=>$v['brand_id'],
                          'name'=>$v['brand']['name']
                      ];
                }

            }
        }
        $data['product']['categories']=$cate_array;
        $data['product']['brand']=$brand_array;

        //请求部分
        $ret = http_web($this->api_url['shop'],[$id])->send();

        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['company'] = $ret['data']['data'];
        }

        //自定义分类
        $categories = http_web($this->api_url['categories'],[$id])->send();

        $search_params=[
            'sp_id'=>$id,
            'sp_logo'=>$data['company']['sp_logo'],
            'company_id'=>$data['company']['sp_cmp_id'],
            'name' =>$search_params['name']
        ];

        $data['shop'] = $search_params;

        $shop = http_web($this->api_url['show'],[$id])->send();
        if(isset($shop['code']) && $shop['code']===0 && !empty($shop['data'])){
            $data['shop'] = $shop['data'];
        }
        $data['search'] = [
            'third_cat' => $this->request->get('third_cat'),
            'custom_cate' => $this->request->get('custom_cate'),
            'brand_id'  => $this->request->get('brand_id'),
            'name'      => $search_params['name'],
            'price'     => $this->request->get('price')
        ];

        $data['categories']=$categories['data'];
//        dd($data);
        try {
            // 检测当前登录用户是否收藏过店铺
            $check = http_web($this->api_url['collection_check'], [0,$id])->send();
            $data['check'] = $check['data'];
            // 检测用户商户是否有 IM 账号
            $shop_uid = $data['shop']['user']['id'];
            $shopImCheck = http_web($this->api_url['shopImCheck'], [$shop_uid])->send();

            $data['shopImCheck'] = isset($shopImCheck['data'])?$shopImCheck['data']:false;
        }catch (\Exception $e){
//            dd($e->getMessage());
        }
//        dd($data);
        return view('web.shop.glists',$data);

    }

    public function archives($id)
    {
        $data = [];
       // 请求部分 archives 信息
        $ret = http_web($this->api_url['archives'],[$id])->send();

        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data = $ret['data'];

            //请求部分 shop 店铺信息
            $shop = http_web($this->api_url['shop'],[$ret['data']['shop']['sp_id']])->send();

            if(isset($shop['code']) && $shop['code']===0 && !empty($shop['data'])){
                $data['company'] = $shop['data']['data'];
            }
            try {
                // 检测当前登录用户是否收藏过店铺
                $check = http_web($this->api_url['collection_check'], [0,$ret['data']['shop']['sp_id']])->send();
                $data['check'] = $check['data'];
                // 检测用户商户是否有 IM 账号
                $shop_uid = $ret['data']['shop']['sp_id'];
                $shopImCheck = http_web($this->api_url['shopImCheck'], [$shop_uid])->send();

                $data['shopImCheck'] = isset($shopImCheck['data'])?$shopImCheck['data']:false;
            }catch (\Exception $e){
                // dd($e->getMessage());
            }
        }
        return view('web.shop.archives',$data);
    }

    /**
     * php 正则验证含非法字符
     * */
    public function CheckIllegalStr($str){

        $data = $this->request->get('str')?$this->request->get('str'):$str;

        $flag = false;
        if (preg_match('/^[a-zA-Z0-9\x{4e00}-\x{9fa5}]+$/u',$data)){
            $flag = true;
        }

        return $flag;
    }

    /**
     * 资质服务
     */

    public function attribute($id)
    {
        //参数部分
        $page = $this->request->get('page', 1);
        $params = [
            'page' => $page,
            'orderBy'=>'id',
            'sortedBy'=>'desc',
        ];

        //请求部分
        $ret = http_web($this->api_url['show'],[$id])->send();

        //结果处理部分
        $data = [];
        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['shop'] = $ret['data'];
        }

        //产品 请求部分
        $ret = http_web($this->api_url['attribute'],[$id])->send($params);
        if(isset($ret['code']) && $ret['code']===0 && !empty($ret['data'])){
            $data['product']= paginate($this->request, $ret['data']);
        }

        if(!empty($data['product']['list'])){
            foreach($data['product']['list'] as $k=>$v){
                $arr=explode(';',$v['attrs']['attributes']);
                foreach($arr as $key=>$val){
                    $arr2=explode(',',$val);
                    $arr[$key]=$arr2;
                    $text='';
                    foreach($arr2 as $key2=>$val2){
                        $arr3=explode(':',$val2);
                        $arr[$key][$key2]=$arr3;
                        if($key>0){
                            $text .= $arr3[1] . '：';
                        }
                        $data['product']['list'][$k]['attrs']['text'][$key]=rtrim($text, '：'); ;
                    }
                }

                $data['product']['list'][$k]['attrs']['level']=isset($arr[0][1][1])?$arr[0][1][1]:'';
                $data['product']['list'][$k]['attrs']['attributes']=$arr;

            }
        }

        $search_params['shop_id'] = $id;
        $data['search_params'] = $search_params;

        try {
            // 检测当前登录用户是否收藏过店铺
            $check = http_web($this->api_url['collection_check'], [0,$id])->send();
            $data['check'] = $check['data'];
            // 检测用户商户是否有 IM 账号
            $shop_uid = $data['shop']['user']['id'];
            $shopImCheck = http_web($this->api_url['shopImCheck'], [$shop_uid])->send();

            $data['shopImCheck'] = isset($shopImCheck['data'])?$shopImCheck['data']:false;
        }catch (\Exception $e){
            //dd($e->getMessage());
        }
//            dd($data);
        return view('web.shop.attributes',$data);

    }







}